/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package multiThreadedressbook;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Cursor;
import java.awt.Desktop;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;

/**
 *
 * @author potirond
 */
public class Controller {
private FormAdd formAdd;
private Contact contact;
private File selection;
private FormModify formModify;
private String toModify = new String();
private static ArrayList<ArrayList> contacts;

public Controller(FormAdd formAdd,Contact contact,FormModify formModify){
    this.formAdd = formAdd;
    this.contact = contact;
    this.formModify = formModify;
    this.formAdd.submit(new Submit());
    this.formAdd.newContact(new NewContact());
    this.formAdd.contactList(new ContactList());
    this.formAdd.delete(new Delete());
    this.formAdd.photo(new Photo());
    this.formAdd.amis(new Amis());
    this.formAdd.all(new All());
    this.formAdd.famille(new Famille());
    this.formAdd.collegues(new Collegues());
    this.formAdd.modify(new Modify());
    this.formModify.modified(new Modified());
    this.formAdd.launchMailBox(new LaunchMail());
    this.formAdd.launchBrowser(new LaunchBrowser());
    this.formAdd.search(new Search());
                try {
                contacts = Contact.read();
                Object data[][]= new Object[contacts.size()-1][2];
                for(int i=1;i<contacts.size();i++){
                    for(int j=0;j<2;j++){
                        data[i-1][j]=contacts.get(i).get(j);
                    }
                }
                String title[] = {"Name","Firstname"};
                this.formAdd.setTable(data, title);
                this.formAdd.setContentPane(this.formAdd.mainPanel);
                this.formAdd.setVisible(true);
                } catch (FileNotFoundException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
    this.formAdd.contactInfo(new ContactInfo());
}
//Action that add a new contact
class Submit implements ActionListener{
    public void actionPerformed(ActionEvent e){
            //Avoid contacts with same name and firstname
            String test= new String();
            String tested = new String();
            int cpt = 0;
            tested=formAdd.name.getText().toString() + " " + formAdd.firstname.getText().toString();
            for(int i=0;i<contacts.size(); i++){
                test=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                if(test.equals(tested)){
                    cpt=1;
                }
            }
            if(cpt==1){
                formAdd.setContentPane(formAdd.p);
                formAdd.setVisible(true);
                JOptionPane.showMessageDialog(formAdd.p, "This contact already exists", "Information", JOptionPane.INFORMATION_MESSAGE);
            }
            else{
                String name,firstname,homeAddress,compagnyAddress,persMobileNum,homeNum,compagnyNum,profMobileNum,email,groups,website;
            String photo;
            if(!formAdd.name.getText().isEmpty()){
            name=formAdd.name.getText();
            }else{name=" ";}
            if(!formAdd.firstname.getText().isEmpty()){
            firstname=formAdd.firstname.getText();
            }else{firstname=" ";}
            if(!formAdd.homeAddress.getText().isEmpty()){
            homeAddress=formAdd.homeAddress.getText();
            }else{homeAddress=" ";}
            if(!formAdd.compagnyAddress.getText().isEmpty()){
            compagnyAddress=formAdd.compagnyAddress.getText();
            }else{compagnyAddress=" ";}
            if(!formAdd.persMobileNum.getText().isEmpty()){
            persMobileNum=formAdd.persMobileNum.getText();
            }else{persMobileNum=" ";}
            if(!formAdd.homeNum.getText().isEmpty()){
            homeNum=formAdd.homeNum.getText();
            }else{homeNum=" ";}
            if(!formAdd.compagnyNum.getText().isEmpty()){
            compagnyNum=formAdd.compagnyNum.getText();
            }else{compagnyNum=" ";}
            if(!formAdd.profMobileNum.getText().isEmpty()){
            profMobileNum=formAdd.profMobileNum.getText();
            }else{profMobileNum=" ";}
            if(!formAdd.email.getText().isEmpty()){
            email=formAdd.email.getText();
            }else{email=" ";}
            photo=formAdd.photo.getText();
            groups=formAdd.groups.getSelectedItem().toString();
            if(!formAdd.website.getText().isEmpty()){
            website=formAdd.website.getText();
            }else{website="www.google.fr";}
            String table[] = new String[2];
            ArrayList newRow=new ArrayList();
            newRow.add(name);newRow.add(firstname);newRow.add(homeAddress);newRow.add(compagnyAddress);newRow.add(persMobileNum);newRow.add(homeNum);newRow.add(compagnyNum);newRow.add(profMobileNum);newRow.add(email);newRow.add(photo);newRow.add(groups);newRow.add(website);
            contacts.add(newRow);
            table[0]=name;
            table[1]=firstname;
            try {
                Contact.newContact(name,firstname,homeAddress,compagnyAddress,persMobileNum,homeNum,compagnyNum,profMobileNum,email,photo,groups,website);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
            formAdd.model.addRow(table);
            formAdd.name.setText("");
            formAdd.firstname.setText("");
            formAdd.homeAddress.setText("");
            formAdd.compagnyAddress.setText("");
            formAdd.persMobileNum.setText("");
            formAdd.homeNum.setText("");
            formAdd.compagnyNum.setText("");
            formAdd.profMobileNum.setText("");
            formAdd.email.setText("");
            formAdd.photo.setText("Click to search photo");
            formAdd.website.setText("");
            formAdd.setVisible(true);
            }  
    }
}

class NewContact extends JFrame implements MouseListener{
        public void mouseClicked(MouseEvent e){
            formAdd.setContentPane(formAdd.p);
            formAdd.setVisible(true);
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(12) );
            formAdd.menuNewContact.setBackground(Color.BLUE);
        }

        public void mouseExited(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(0) );
        }

}

class ContactList implements MouseListener{
        public void mouseClicked(MouseEvent e){
            formAdd.setContentPane(formAdd.mainPanel);
            formAdd.setVisible(true);

        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(12) );
        }

        public void mouseExited(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(0) );
        }
}

class Delete implements ActionListener{
    public void actionPerformed(ActionEvent e){
            int selectedRow = formAdd.table.convertRowIndexToModel(formAdd.table.getSelectedRow());
            //on récupère la valeur de la première colonne de la ligne sélectionné
            Object o[] = new Object[2];
            o[0]= formAdd.model.getValueAt(selectedRow, 0);
            o[1] = formAdd.model.getValueAt(selectedRow, 1);
            String toDelete = o[0].toString() + " " + o[1].toString();
            String s = new String();
            formAdd.model.removeRow(selectedRow);
            for(int i=0;i<contacts.size(); i++){
                s=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                if(toDelete.equals(s)){
                    //remove line from the list
                    contacts.remove(contacts.get(i));
                }
            }
            Thread ta=new Thread((Runnable) contact);
            //rewrite the file with the list with removed line
            ta.start();
            formAdd.repaint();
            formAdd.setVisible(true);           
    }
}

class ContactInfo implements ListSelectionListener{
    public void valueChanged(ListSelectionEvent event) {
        try {
            if(formAdd.table.getSelectedRow()>-1){
            formAdd.infoHeadEst.removeAll();
            formAdd.infoHead.removeAll();
            formAdd.infoBody.removeAll();
            int selectedRow = formAdd.table.convertRowIndexToModel(formAdd.table.getSelectedRow());
            String c = formAdd.model.getValueAt(selectedRow, 0).toString() + " " + formAdd.model.getValueAt(selectedRow, 1).toString();
            String s = new String();
            for(int i=1; i<contacts.size(); i++){
                s=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                if(s.equals(c)){
                        formAdd.setLabels(contacts.get(i).get(0).toString(),contacts.get(i).get(1).toString(),contacts.get(i).get(2).toString(),contacts.get(i).get(3).toString(),contacts.get(i).get(4).toString(),contacts.get(i).get(5).toString(),contacts.get(i).get(6).toString(),contacts.get(i).get(7).toString(),contacts.get(i).get(8).toString(),contacts.get(i).get(9).toString(),contacts.get(i).get(10).toString(),contacts.get(i).get(11).toString());
                }
            }
            formAdd.setContentPane(formAdd.mainPanel);
            formAdd.setVisible(true);
            }
            } catch (IOException ex) {
                        //Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                    }
    }
}

public class Photo implements ActionListener{
    public void actionPerformed(ActionEvent e){
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        selection = chooser.getSelectedFile();
        formAdd.photo.setText(selection.getAbsolutePath());
        }
    }
}

public class Amis implements ActionListener{
    public void actionPerformed(ActionEvent e){
            ArrayList<ArrayList> contacts2 = new ArrayList<ArrayList>();
            for(int i=0;i<contacts.size(); i++){
                if(contacts.get(i).get(10).toString().equals("amis")){
                    contacts2.add(contacts.get(i));
                }
            }
            if (formAdd.model.getRowCount() > 0) {
                for (int i = formAdd.model.getRowCount() - 1; i > -1; i--) {
                    formAdd.model.removeRow(i);
                }
            }
            for(int i=0;i<contacts2.size(); i++){
                formAdd.model.addRow(contacts2.get(i).toArray());
            }
    }
}

public class All implements ActionListener{
    public void actionPerformed(ActionEvent e){
            if (formAdd.model.getRowCount() > 0) {
                for (int i = formAdd.model.getRowCount() - 1; i > -1; i--) {
                    formAdd.model.removeRow(i);
                }
            }
            for(int i=1;i<contacts.size(); i++){
                formAdd.model.addRow(contacts.get(i).toArray());
            }
    }
}

public class Famille implements ActionListener{
    public void actionPerformed(ActionEvent e){
            ArrayList<ArrayList> contacts2 = new ArrayList<ArrayList>();
            for(int i=0;i<contacts.size(); i++){
                if(contacts.get(i).get(10).toString().equals("famille")){
                    contacts2.add(contacts.get(i));
                }
            }
            if (formAdd.model.getRowCount() > 0) {
                for (int i = formAdd.model.getRowCount() - 1; i > -1; i--) {
                    formAdd.model.removeRow(i);
                }
            }
            for(int i=0;i<contacts2.size(); i++){
                formAdd.model.addRow(contacts2.get(i).toArray());
            }
    }
}

public class Collegues implements ActionListener{
    public void actionPerformed(ActionEvent e){
            ArrayList<ArrayList> contacts2 = new ArrayList<ArrayList>();
            for(int i=0;i<contacts.size(); i++){
                if(contacts.get(i).get(10).toString().equals("collègues")){
                    contacts2.add(contacts.get(i));
                }
            }
            if (formAdd.model.getRowCount() > 0) {
                for (int i = formAdd.model.getRowCount() - 1; i > -1; i--) {
                    formAdd.model.removeRow(i);
                }
            }
            for(int i=0;i<contacts2.size(); i++){
                formAdd.model.addRow(contacts2.get(i).toArray());
            }
    }
}

public class Modify implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if(formAdd.table.getSelectedRow()>-1){
                int selectedRow = formAdd.table.convertRowIndexToModel(formAdd.table.getSelectedRow());
                String c = formAdd.model.getValueAt(selectedRow, 0).toString() + " " + formAdd.model.getValueAt(selectedRow, 1).toString();
                String s =new String();
                for(int i=1; i<contacts.size(); i++){
                    s=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                    if(s.equals(c)){
                        formModify.setFields(contacts.get(i).get(0).toString(),contacts.get(i).get(1).toString(),contacts.get(i).get(2).toString(),contacts.get(i).get(3).toString(),contacts.get(i).get(4).toString(),contacts.get(i).get(5).toString(),contacts.get(i).get(6).toString(),contacts.get(i).get(7).toString(),contacts.get(i).get(8).toString(),contacts.get(i).get(9).toString(),contacts.get(i).get(10).toString(),contacts.get(i).get(11).toString());
                        toModify=s;
                    }
                }
        }
    }
}

public class Modified implements ActionListener{
    public void actionPerformed(ActionEvent e){
            ArrayList modif=formModify.getFields();
            String s = new String();
            for(int i=0;i<contacts.size(); i++){
                s=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                if(toModify.equals(s)){
                    //remove line from the list
                    contacts.remove(contacts.get(i));
                }
            }
            contacts.add(modif); // add the modified contact at the list
            Thread ta=new Thread((Runnable) contact);
            //rewrite the file with the list with removed line
            ta.start();
            for(int i=0;i<formAdd.model.getRowCount(); i++){
                s=formAdd.table.getValueAt(i, 0).toString() + " " + formAdd.table.getValueAt(i, 1).toString();
                if(toModify.equals(s)){
                    //remove line from the list
                    formAdd.model.removeRow(formAdd.table.convertRowIndexToModel(i));
                }
            }
            String table[] = new String[2];
            table[0]=modif.get(0).toString();
            table[1]=modif.get(1).toString();
            formAdd.model.addRow(table);
            formAdd.table.setRowSelectionInterval(formAdd.model.getRowCount()-1, formAdd.model.getRowCount()-1);
            formModify.setVisible(false);
            formAdd.repaint();
            formAdd.setVisible(true);
    }
}

class LaunchMail implements MouseListener{
        public void mouseClicked(MouseEvent e){
            if(Desktop.isDesktopSupported()){
                if(Desktop.getDesktop().isSupported(java.awt.Desktop.Action.MAIL)){
                    try {
                            java.awt.Desktop.getDesktop().mail(new java.net.URI("mailto:" + formAdd.infoEmail.getText()));
                    } catch (IOException ex) {
                        //Traitement de l'exception
                    }   catch (URISyntaxException ex) {
                            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    } 
                else {
                            //La fonction de mail n'est pas supportée par votre système d'exploitation
                }
            }
            else {
	//Desktop pas supportée par votre système d'exploitation
            }
            formAdd.setContentPane(formAdd.mainPanel);
            formAdd.setVisible(true);

        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(12) );
        }

        public void mouseExited(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(0) );
        }
}

class LaunchBrowser implements MouseListener{
        public void mouseClicked(MouseEvent e){
            if ( Desktop.isDesktopSupported() ) {
                // On récupère l'instance du desktop :
                Desktop desktop = Desktop.getDesktop();
 
            // On vérifie que la fonction browse est bien supportée :
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                    try {
                        // Et on lance l'application associé au protocole :
                        desktop.browse(new URI("http://" + formAdd.infoWebsite.getText()));
                    } catch (IOException ex) {
                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (URISyntaxException ex) {
                        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                    }
	}
}
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(12) );
        }

        public void mouseExited(MouseEvent e) {
            formAdd.setCursor( Cursor.getPredefinedCursor(0) );
        }
}

class Search implements DocumentListener{
        public void insertUpdate(DocumentEvent e) {
            try {
                String s = new String();
                String c = new String();
                s=e.getDocument().getText(0, e.getDocument().getLength());
                for(int i=0;i<formAdd.table.getRowCount();i++){
                    c=formAdd.table.getValueAt(i, 0).toString() + " " + formAdd.table.getValueAt(i, 1).toString();
                    if(c.toLowerCase().contains(s.toLowerCase())){}
                    else{
                        formAdd.model.removeRow(formAdd.table.convertRowIndexToModel(i));
                        i--;
                    }
                }
            } catch (BadLocationException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void removeUpdate(DocumentEvent e) {
            try {
                String s = new String();
                String c = new String();
                String[] table = new String[2];
                s=e.getDocument().getText(0, e.getDocument().getLength());
                if (formAdd.model.getRowCount() > 0) {
                    for (int i = formAdd.model.getRowCount() - 1; i > -1; i--) {
                        formAdd.model.removeRow(i);
                    }
                }
                for(int i=1;i<contacts.size();i++){
                    c=contacts.get(i).get(0).toString() + " " + contacts.get(i).get(1).toString();
                    if(c.toLowerCase().contains(s.toLowerCase())){
                        table[0]=contacts.get(i).get(0).toString();
                        table[1]=contacts.get(i).get(1).toString();
                        formAdd.model.addRow(table);
                    }
                    else{
                    }
                }
            } catch (BadLocationException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void changedUpdate(DocumentEvent e) {
            
        }
    
}

public static ArrayList<ArrayList> getContacts(){
    return contacts;
}
}
